package Thread;

import java.util.concurrent.TimeUnit;

/**
 * @author VX5
 * @Title: MJC
 * @ProjectName DataStructure
 * @Description: TODO
 * @date ${DAT}14:38
 */
public class WaitNotify {
    static boolean falg = true;
    static Object lock = new Object();

    public static void main(String[] args) throws InterruptedException {
        Thread waitThread = new Thread(new Wait(),"WaitThread");
        waitThread.start();
        TimeUnit.SECONDS.sleep(1);
        Thread notifyAll = new Thread(new Notify(),"Notify");
        notifyAll.start();
    }

    static class Wait implements Runnable{

        @Override
        public void run() {
            synchronized (lock){
                System.out.println("开始等消息");
                try {
                    while (falg) {//这里循环是因为 ： notify/notifyAll 执行后，等待线程依旧不会从wait()返回，需要调用notify/notifyAll的线程释放锁后，等待线程才有可能从wait()返回。
                        lock.wait();
//                        System.out.println("消息快到了");
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("收到消息");
        }
    }

    static class Notify  implements Runnable{

        @Override
        public void run() {
            synchronized (lock){
                System.out.println("发送消息");
                lock.notifyAll();
                falg = false;
                try {
                    SleepUtils.second(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //再次加锁
            synchronized (lock){
                System.out.println(Thread.currentThread()+"hold clock");
                try {
                    SleepUtils.second(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
